package com.walkline.util.ui;

import java.util.Vector;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.DrawTextParam;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.TextMetrics;
import net.rim.device.api.ui.component.ActiveRichTextField;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.component.TextField;
import net.rim.device.api.ui.text.TextFilter;

import com.walkline.app.WeiboAppConfig;
import com.walkline.util.Emotions;
import com.walkline.util.Enumerations.Themes;
import com.walkline.util.Function;
import com.walkline.util.StringUtility;
import com.walkline.util.me.regexp.RE;
import com.walkline.weibo.inf.Status;

public class TestStatusListStyleButtonField extends Field
{
    public static int DRAWPOSITION_TOP = 0;
    public static int DRAWPOSITION_BOTTOM = 1;
    public static int DRAWPOSITION_MIDDLE = 2;
    public static int DRAWPOSITION_SINGLE = 3;

    private static final int CORNER_RADIUS = 0;

    private static boolean needSmallIcon = Display.getWidth() < 640 ? true : false;

    private static final int HPADDING = Display.getWidth() <= 320 ? 4 : 6;
    private static final int VPADDING = 4;

    private static int COLOR_TIME = 0x6F6F6F;
    private static int COLOR_TIME_FOCUS = 0x6F6F6F;
    private static int COLOR_SOURCE = 0x6F6F6F;
    private static int COLOR_SOURCE_FOCUS = 0x6F6F6F;//0X6271FA;
    private static int COLOR_COUNTS = 0x6F6F6F;
    private static int COLOR_COUNTS_FOCUS = 0x6F6F6F;
    private static int COLOR_SCREENNAME = 0xDFDFDF;
    private static int COLOR_SCREENNAME_FOCUS = 0xDFDFDF; //DFDFDF;
    private static int COLOR_STATUS = 0xB4B4B4;
    private static int COLOR_STATUS_FOCUS = 0xB4B4B4; //0xAFAFAF;
    private static int COLOR_RETWEETED = 0x646464;
    private static int COLOR_RETWEETED_FOCUS = 0x646464; //0x7F7F7F;
    private static int COLOR_BACKGROUND = Color.BLACK;
    private static int COLOR_BACKGROUND_FOCUS = 0x1A1A1A; //0x071A37; //0x031A32; //0x062f67;//0x030D1B;
    //private static final int COLOR_BORDER = COLOR_BACKGROUND; //0xBBBBBB;
    //private static final int COLOR_BORDER_FOCUS = COLOR_BACKGROUND_FOCUS;//0xBBBBBB;

    private MyLabelField _labelScreenName;
    private MyLabelFieldWithNewline _labelText;
    private MyLabelField _labelTime;
    private MyLabelField _labelSource;
    private MyLabelField _labelCounts;

    private static Font FONT_SCREENNAME = WeiboAppConfig.FONT_SCREENNAME;
	private static Font FONT_SOURCE = WeiboAppConfig.FONT_SOURCE;

    private Bitmap _avatarIcon;
    private Bitmap[] _images_Status = null;

    private int _rightOffset;
    private int _leftOffset;
    private int _labelHeight;

    private WeiboAppConfig _appConfig;
    private Emotions _emotions = Emotions.getInstance();
    private String[][][] _all_emotions = _emotions.getAllEmotions();
    private int _drawPosition = -1;

    Bitmap em = Bitmap.getBitmapResource("d_doge.png");

    public TestStatusListStyleButtonField(WeiboAppConfig appConfig, Status status)
    {
        super(USE_ALL_WIDTH | Field.FOCUSABLE);

        try {
            _appConfig = appConfig;

        	String screen_name = status.getUser().getScreenName() + (!status.getUser().getRemark().equals("") ? "(" + status.getUser().getRemark() + ")" : "");
        	String time = status.getCreatedAtShort();
        	String text = status.getText();

//        	int fromIndex = 0;
//        	int startPos = 0;
//        	int endPos = 0;
//        	String emotion = "";
//        	while (true)
//        	{
//        		startPos = text.indexOf("[", fromIndex);
//        		if (startPos != -1)
//        		{
//        			endPos = text.indexOf("]", startPos);
//        			if (endPos != -1)
//        			{
//        				emotion = text.substring(startPos, endPos + 1);
//        				for (int i=0; i<_emotions.getGroupCount(); i++)
//        				{
//        					for (int j=0; j<_emotions.getCount(i); j++)
//        					{
//        						if (emotion.equals(_all_emotions[i][j][0]))
//        						{
//        							emotion = _all_emotions[i][j][1];
//
//        							if (startPos == 0)
//        							{
//        								text = "[  ]" + text.substring(endPos + 1);
//        							} else {
//        								text = text.substring(0, startPos - 1) + "[ ]" + text.substring(endPos + 1);	
//        							}
//
//        							i = _emotions.getGroupCount() - 1;
//        						}
//        					}
//        				}
//
//        				//Function.errorDialog("emotion: " + emotion + "\nfrom: " + startPos + "\nto: " + endPos);
//        				fromIndex = endPos + 1;
//        			} else {
//        				break;
//        			}
//        		} else {
//        			break;
//        		}
//        	}

//        	RE re = new RE();
//
//        	re = new RE("\\[[^.,:;!?（）\\s#@。，：；！？]*\\]"); //"\\[(.*)\\]");
//    		if (re.match(text))
//    		{
//    			Vector result = re.getMatchResult();
//
//    			for (int i=0; i<result.size(); i++)
//    			{
//    				Function.errorDialog("result " + i + ": " + result.elementAt(i));
//    				text = StringUtility.replace(text, (String) result.elementAt(i), "[空格]");
//    			}
//    		}

        	String source = status.getSource() != null ? status.getSource().getName() : null;
        	String[] images = status.getPicUrls().getCount() > 1 ? status.getPicUrls().getSquarePics() : status.getPicUrls().getThumbnailPics();
        	String counts = status.getRepostsCount() > 0 ? "转 " + status.getRepostsCount() : "";
        	counts += status.getCommentsCount() > 0 ? (!counts.equals("") ? " | " : "") + "评 " + status.getCommentsCount() : "";
        	counts += status.getAttitudesCount() > 0 ? (!counts.equals("") ? " | " : "") + "赞 " + status.getAttitudesCount() : "";

        	_avatarIcon = Bitmap.getBitmapResource("avatar.png");

        	RichTextField a = new RichTextField() {
        		protected void layout(int width, int height) {
        			// TODO Auto-generated method stub
        			super.layout(width, height);
        		}
        	};

            if (screen_name != null) {_labelScreenName = new MyLabelField(screen_name);}
            if (time != null) {_labelTime = new MyLabelField(time, 0);}
            if (text != null) {
            	_labelText = new MyLabelFieldWithNewline(text);

            	int fromIndex = 0;
            	int startPos = 0;
            	int endPos = 0;
            	String emotion = "";
            	while (true)
            	{
            		startPos = text.indexOf("[", fromIndex);
            		if (startPos != -1)
            		{
            			endPos = text.indexOf("]", startPos);
            			if (endPos != -1)
            			{
            				emotion = text.substring(startPos, endPos + 1);
            				for (int i=0; i<_emotions.getGroupCount(); i++)
            				{
            					for (int j=0; j<_emotions.getCount(i); j++)
            					{
            						if (emotion.equals(_all_emotions[i][j][0]))
            						{
            							//emotion = _all_emotions[i][j][1];

            							TextMetrics metrics = new TextMetrics();
            							DrawTextParam param = new DrawTextParam();
            							if (startPos == 0)
            							{
            								//text = "[  ]" + text.substring(endPos + 1);
            								_labelText.getFont().measureText(text, 0, 4 , param, metrics);
            							} else {
            								//text = text.substring(0, startPos - 1) + "[ ]" + text.substring(endPos + 1);	
            								_labelText.getFont().measureText(text, startPos - 1, 4, param, metrics);
            							}

            							i = _emotions.getGroupCount() - 1;

            							//Function.errorDialog("advanceY: " + metrics.getAdvanceY() + "\nleft: " + metrics.getBoundsLeft());
            						}
            					}
            				}

            				//Function.errorDialog("emotion: " + emotion + "\nfrom: " + startPos + "\nto: " + endPos);
            				fromIndex = endPos + 1;
            			} else {
            				break;
            			}
            		} else {
            			break;
            		}
            	}
            }
            if (source != null) {_labelSource = new MyLabelField("来自 " + source, 0);}
            if (!counts.equals("")) {_labelCounts = new MyLabelField(counts, 0);}
            if (images != null)
            {
            	int count = status.getPicUrls().getCount();

            	if (count > 0)
            	{
            		if (needSmallIcon)
            		{
            			if (count > 3) {count = 4;}	
            		} else {
            			if (count > 5) {count = 6;}
            		}

                	_images_Status = new Bitmap[count];

               		for (int i=0; i<count; i++)
                   	{
                   		_images_Status[i] = Bitmap.getBitmapResource("status_image_multi.png");
                   	}
            	}
            }
		} catch (Exception e) {
			Function.errorDialog(e.toString());
		}

        setThemesColor();
        setFontSize();
    }

    private void setFontSize()
    {
    	if (_labelScreenName != null) {_labelScreenName.setFont(FONT_SCREENNAME);}
    	if (_labelSource != null) {_labelSource.setFont(FONT_SOURCE);}
    	if (_labelCounts != null) {_labelCounts.setFont(FONT_SOURCE);}
    }

    private void setThemesColor()
    {
    	int[] currentThemesValue = Themes.choicesThemesValue[_appConfig.getThemes()];

    	COLOR_BACKGROUND = currentThemesValue[0];
    	COLOR_BACKGROUND_FOCUS = currentThemesValue[1];
    	COLOR_SCREENNAME = currentThemesValue[2];
    	COLOR_SCREENNAME_FOCUS = currentThemesValue[3];
    	COLOR_STATUS = currentThemesValue[4];
    	COLOR_STATUS_FOCUS = currentThemesValue[5];
    	COLOR_RETWEETED = currentThemesValue[6];
    	COLOR_RETWEETED_FOCUS = currentThemesValue[7];
    	COLOR_TIME = currentThemesValue[8];
    	COLOR_TIME_FOCUS = currentThemesValue[9];
    	COLOR_SOURCE = currentThemesValue[10];
    	COLOR_SOURCE_FOCUS = currentThemesValue[11];
    	COLOR_COUNTS = currentThemesValue[12];
    	COLOR_COUNTS_FOCUS = currentThemesValue[13];
    }

    public void setDrawPosition( int drawPosition ) {_drawPosition = drawPosition;}

    public int getPreferredHeight() {return _labelHeight;}

    public void layout(int width, int height)
    {
    	_labelHeight = VPADDING;
        _leftOffset = HPADDING;
        _rightOffset = HPADDING;
        
        if (_avatarIcon != null) {_leftOffset += _avatarIcon.getWidth() + HPADDING;}

        if (_labelTime != null) {_labelTime.layout(width- _leftOffset - _rightOffset, height);}
        
        if (_labelScreenName != null)
        {
        	int intWidth = _labelTime != null ? _labelTime.getWidth() : 0;
        	_labelScreenName.layout(width - _leftOffset - _rightOffset - intWidth, height);
            _labelHeight += _labelScreenName.getHeight();	
        }

        if (_labelText != null)
        {
        	_labelText.layout(width - _leftOffset - _rightOffset, height);
        	_labelHeight += _labelText.getHeight() + VPADDING;
        }

        if (_avatarIcon != null) {_labelHeight = (_avatarIcon.getHeight() >= _labelHeight) ? _avatarIcon.getHeight() + 2 * VPADDING : _labelHeight;}

        if (_labelSource != null)
        {
        	_labelSource.layout(width - _leftOffset - _rightOffset, height);
        	_labelHeight += _labelSource.getHeight() + 2 * VPADDING;

        	if (_labelCounts != null) {_labelCounts.layout(width - _leftOffset - _rightOffset, height);}
        } else if (_labelCounts != null) {
        	_labelCounts.layout(width - _leftOffset - _rightOffset, height);
        	_labelHeight += _labelCounts.getHeight() + 2 * VPADDING;
        } else {
        	_labelHeight += VPADDING;
        }

        setExtent(width, _labelHeight);
    }

    protected void paint(Graphics g)
    {
    	int currentTop = VPADDING;

        // Avatar Bitmap
        if (_avatarIcon != null) {g.drawBitmap(HPADDING, currentTop, _avatarIcon.getWidth(), _avatarIcon.getHeight(), _avatarIcon, 0, 0);}

        // Screen name Text
        try {
        	g.setColor(g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS) ? COLOR_SCREENNAME_FOCUS : COLOR_SCREENNAME);
        	g.setFont(FONT_SCREENNAME);
            g.pushRegion(_leftOffset, currentTop, getWidth() - _leftOffset - _rightOffset, _labelScreenName.getHeight(), 0, 0);
            _labelScreenName.paint(g);
        } finally {g.popContext();}

        // Time Text
        if (_labelTime != null)
        {
        	try {
        		g.setColor(g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS) ? COLOR_TIME_FOCUS : COLOR_TIME);
        		g.pushRegion(getWidth() - _labelTime.getWidth()-_rightOffset, currentTop, _labelTime.getWidth(), _labelTime.getHeight(),0,0);
        		_labelTime.paint(g);
        	} finally{g.popContext();}
        }

        // Status Text
        if (_labelText != null)
        {
        	currentTop += _labelScreenName.getHeight();

        	try {
        		g.setColor(g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS) ? COLOR_STATUS_FOCUS : COLOR_STATUS);
        		g.pushRegion(_leftOffset + HPADDING, currentTop, getWidth()-_leftOffset-_rightOffset, _labelText.getHeight(), 0, 0);
        		_labelText.paint(g);

        		g.drawBitmap(0, 0, em.getWidth(), em.getHeight(), em, 0, 0);
        	} finally{g.popContext();}

        	currentTop += _labelText.getHeight() + VPADDING;

            if (_images_Status != null)
            {
            	int xOffset = _leftOffset + HPADDING;
            	int count = _images_Status.length;

            	if (needSmallIcon)
        		{
        			if (count > 3) {count = 4;}	
        		} else {
        			if (count > 5) {count = 6;}
        		}

            	for (int i=0; i<count; i++)
            	{
            		g.drawBitmap(xOffset, currentTop, _images_Status[i].getWidth(), _images_Status[i].getHeight(), _images_Status[i], 0, 0);
            		xOffset += _images_Status[i].getWidth() + HPADDING * 2;
            	}

           		currentTop += _images_Status[0].getHeight() + VPADDING;
            }
        }

        // Source
        if (_labelSource != null)
        {
        	if (currentTop < _avatarIcon.getHeight())
        	{
        		currentTop = _avatarIcon.getHeight() + 3 * VPADDING;
        	} else {
        		currentTop += VPADDING;	
        	}

    		try {
    			g.setColor(g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS) ? COLOR_SOURCE_FOCUS : COLOR_SOURCE);
    			g.setFont(FONT_SOURCE);
        		g.pushRegion(2 * HPADDING, currentTop, _labelSource.getWidth(), _labelSource.getHeight(), 0, 0);
        		_labelSource.paint(g);
        	} finally{g.popContext();}
        }

        // Reply counts
        if (_labelCounts != null)
		{
    		try {
    			g.setColor(g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS) ? COLOR_COUNTS_FOCUS : COLOR_COUNTS);
    			g.setFont(FONT_SOURCE);
        		g.pushRegion(getWidth() - _labelCounts.getWidth() - _rightOffset, currentTop, _labelCounts.getWidth(), _labelCounts.getHeight(), 0, 0);
        		_labelCounts.paint(g);
        	} finally{g.popContext();}
		}
    }

    protected void paintBackground(Graphics g)
    {
        if (_drawPosition < 0)
        {
            super.paintBackground(g);
            return;
        }

        int oldColour = g.getColor();

        int background = g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS) ? COLOR_BACKGROUND_FOCUS : COLOR_BACKGROUND;

        try {
            if (_drawPosition == 0)
            {
                // Top
                g.setColor(background);
                g.fillRoundRect(0, 0, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
                //g.setColor(COLOR_BORDER);
                g.drawRoundRect(0, 0, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
                g.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1);
            } else if(_drawPosition == 1) {
                // Bottom 
                g.setColor(background);
                g.fillRoundRect(0, -CORNER_RADIUS, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
                //g.setColor(COLOR_BORDER);
                g.drawRoundRect(0, -CORNER_RADIUS, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
            } else if(_drawPosition == 2) {
                // Middle
                g.setColor(background);
                g.fillRoundRect(0, -CORNER_RADIUS, getWidth(), getHeight() + 2 * CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
                //g.setColor(COLOR_BORDER);
                g.drawRoundRect(0, -CORNER_RADIUS, getWidth(), getHeight() + 2 * CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
                g.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1);
            } else {
                // Single
                g.setColor(background);
                g.fillRoundRect(0, 0, getWidth(), getHeight(), CORNER_RADIUS, CORNER_RADIUS);
                //g.setColor(COLOR_BORDER);
                g.drawRoundRect(0, 0, getWidth(), getHeight(), CORNER_RADIUS, CORNER_RADIUS);
            }
        } finally {
            g.setColor(oldColour);
        }
    }

    protected void drawFocus(Graphics g, boolean on)
    {
        if(_drawPosition < 0)
        {
            super.drawFocus(g, on);
        } else {
            boolean oldDrawStyleFocus = g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS);

            try {
                if(on)
                {
                	g.setColor(Color.WHITE);
                    g.setDrawingStyle(Graphics.DRAWSTYLE_FOCUS, true);
                }

                paintBackground(g);
                paint(g);
            } finally {
                g.setDrawingStyle(Graphics.DRAWSTYLE_FOCUS, oldDrawStyleFocus);
            }
        }
    }

    public void setDirty( boolean dirty ) {}
    public void setMuddy( boolean muddy ) {}
}